<?php

YII::import('dao.bid.*');
YII::import('application.extensions.YiiMailer.YiiMailer');
Yii::import('dao.share.class.InviteEmail');
class ApiController extends Controller{

	
	public function init(){
		parent::init();
	}
	/**
	 * 自动登录
	 * 后台管理员登录
	 * egunner同步登录
	 */
	public function actionAutoLogin(){

		$username = $_GET['username'];
		$Login_info=$this->check($username);

		if(!empty($Login_info)){
			$login_auth=new SysAuth();
			$login_auth->id       = $Login_info['id'];
			$login_auth->username = $Login_info['user_name'];
			if(!empty($_GET['admin'])){
			    Yii::app()->user->admin=$_GET['admin'];
			    $_SESSION['is_admin']="yes";
			}			
			$result = LoginPlus::Login($login_auth);			
		}
	}
	
	/**
	 * 同步登出
	 */
	public function actionAutoLogout(){
	    Yii::app()->user->logout(true);
	}
	
	public function actionAutoRegisterSync(){
	    $data=$_REQUEST;
	    $user_data=$this->setSyncUserData($data);
	    if(!empty($user_data)){
	        $uniqid=$this->createUniqid();
	        $customer=new Customer();
	        $dao = new RegisterEgunnerDao();
	        $dao->attributes=$user_data;
	        $dao->created=$user_data['created'];
	        $dao->status=1;
	        $dao->salt=$user_data['salt'];
	        $dao->avatar=Yii::app()->resource->path('')."/images/avatar/headimg1.jpg";
	        $dao->ip=Yii::app()->tools->getIp();
	        $dao->birthday=$user_data['birthday'];
	        $dao->refer=$uniqid;
	
	        $result=$dao->save();
	        Yii::app()->cache->set('regis',$dao);
	        if($result){
	            $customer_info=$customer->findAllByAttributes(array("email"=>$user_data['email']));
	            $bid = new BidDao();
	            $bid->customerId=$customer_info[0]->id;
	            $bid->getBidModel('cash')->setBid(5,'Register');
	            //发送邮件通知注册成功，赠送5个PROMO BID
	            // 时间，用户名，赠BID数量
	        }
	       var_dump($result);
	    }
	}
	public function setSyncUserData($data){
	    $user_data=array();
	    $user_data['first_name']=$data['first_name'];
	    $user_data['last_name']=$data['last_name'];
	    $user_data['address']=$data['address'];
	    $user_data['city']=$data['city'];
	    $user_data['zip_code']=$data['zip_code'];
	    $user_data['states']=$data['state'];
	    $user_data['phone']=$data['phone_a']?$data['phone_a']:111;
	    $user_data['birthday']=$data['birthday'];
	    $user_data['email']=$data['email'];
	    $user_data['conemail']=$data['email'];
	    $user_data['is_agree']=1;
	    $user_data['created']=$data['created'];
	    $user_data['conpassword']=$data['password'];
	    $user_data['user_name']=$data['username'];
	    $user_data['password']=$data['password'];
	    $user_data['salt']=$data['salt'];
	    return $user_data;
	}
	/*
	* 同步注册
	*/
    public function actionAutoRegister(){
            $data=$_REQUEST;
            $user_data=$this->setUserData($data);
            if(!empty($user_data)){
                $uniqid=$this->createUniqid();
                $customer=new Customer();
                $dao = new RegisterEgunnerDao();
                $dao->attributes=$user_data;
                $dao->created=time();
                $dao->status=1;
                $dao->salt=$user_data['salt'];
                $dao->avatar=Yii::app()->resource->path('')."/images/avatar/headimg1.jpg";
                $dao->ip=Yii::app()->tools->getIp();
                $dao->birthday=$user_data['birthday'];
                $dao->refer=$uniqid;
                
                $result=$dao->save();
                Yii::app()->cache->set('regis',$dao);
                if($result){
                    $customer_info=$customer->findAllByAttributes(array("email"=>$user_data['email']));
                    $bid = new BidDao();
                    $bid->customerId=$customer_info[0]->id;
                    $bid->getBidModel('cash')->setBid(5,'Register');
                    //发送邮件通知注册成功，赠送5个PROMO BID
                    // 时间，用户名，赠BID数量
                }
            }
    }
    /*
     * 同步修改个人信息
     */
    public function actionAutoUpdate(){
        $data=$_REQUEST;
        
        $customer_info=new CustomerInfo();
        $customer=Customer::model()->find('user_name="'.$data["username"].'"');
        if(!empty($customer)){
            $customer_info->updateAll(array(
                'first_name'=>$data['first_name'],
                'last_name'=>$data['last_name'],
                'address'=>$data['address'],
                'city'=>$data['city'],
                'zip_code'=>$data['zip_code'],
                'state'=>$data['state'],
                'phone'=>$data['phone'],         
            ),
                'customer_id='.$customer->id
                );
        }       
    }
    /*
     * 同步修改密码
     */
    public function actionAutoPassword(){
        $data=$_REQUEST;
        $customer=Customer::model()->find('user_name="'.$data["username"].'"');
        if(!empty($customer)){
            $customer->updateAll(array(
                'password'=>$data['password'],
                'salt'    =>$data['salt'],
            ),'user_name="'.$data['username'].'"'
                );
        }      
    }
    public function actionGetCache(){
        $name=$_GET['name'];
        var_dump(Yii::app()->cache->get($name));
    }
	/*
	 * 数据重构
	 */
    public function setUserData($data){
        $user_data=array();
        $user_data['first_name']=$data['first_name'];
        $user_data['last_name']=$data['last_name'];
        $user_data['address']=$data['address'];
        $user_data['city']=$data['city'];
        $user_data['zip_code']=$data['zip_code'];
        $user_data['state']=$data['state'];
        $user_data['phone']=$data['phone_a'].$data['phone_b'];
        $user_data['birthday']=strtotime($data['dob_month']."/".$data['dob_day']."/".$data['dob_year']);
        $user_data['email']=$data['email'];
        $user_data['conemail']=$data['email'];
        $user_data['is_agree']=1;
        $user_data['conpassword']=$data['password'];
        $user_data['user_name']=$data['username'];
        $user_data['password']=$data['password'];
        $user_data['salt']=$data['salt'];
        return $user_data;
    }
    /**
     * @param $email str 自动登录时候获取的用户名，用于检验和查找ID和账号
     * @return array 用户的ID和账号
     * @author zhanglei 2015.10.10
     */
	public function check($username=null){

		$user=new Customer();
		$user=$user->findByAttributes(array('user_name'=>$username));
		$login_info=$user->attributes;
		return $login_info;

	}
	public static function createUniqid(){
		 
	    $tempStr = md5(time());
	    return $tempStr[mt_rand(0,31)].uniqid();
	}
	public function actionInsertAutobidData(){
	    $customerId=Yii::app()->getRequest()->getParam("cid");
	    $tablename = Method::getBidHistoryUserTableName($customerId);
	    $bidSQL = 'insert into '.$tablename.' (customer_id,bid_source_type,amount,bid_type,action,note,auction_id,created) 
	        SELECT customer_id,bid_source_type,amount,bid_type,"COST" as action,note,auction_id,created 
	        FROM `auction_bid_log` 
	        where customer_id='.$customerId.' and bid_source_type="AUTO_BID"';
	    $updateInfoBid = Yii::app()->db->createCommand($bidSQL)->execute();
	    var_dump($updateInfoBid);
	}
	
	/**
	 * 主站调用接口，返回json格式feature acution数据
	 */
	public function actionGetFeatureAuctions(){
	    $result=[];
	    $max=Yii::app()->getRequest()->getParam("max",20);
	    $featureModel=new AuctionPoolProvider();
        $featureModel->search_category_id = 'feature';
        $featureModel->limit=$max;
        $dataProvider = $featureModel->searchForFeature();
        $data=$dataProvider->data;
        if (!empty($data)){
            foreach ($data as $dataItem){
                $tempItem=[
                    "productId"=>$dataItem->auction_id,
                    "productName"=>$dataItem->title,
                    "currentBidPrice"=>$dataItem->winner_price,
                    "productImageUrl"=>$dataItem->images,
                    "endTime"=>$dataItem->end_time,
                    "start_price"=>100000,
                    "reserve_price"=>100000,
                    "detailUrl"=>AuctionInfo::urlencode($dataItem->title)
                ];
                $result[]=$tempItem;
            }
        }
        echo json_encode($result,JSON_ERROR_SYNTAX);
	}
}